#!/usr/bin/env python

import sys
import shutil

if len(sys.argv) != 2:
  print >>sys.stderr, 'Usage: %s <file>' % (sys.argv[0])
  sys.exit(1)

_PATCH = ('public java.util.Map<'
          'com.google.protobuf.Descriptors.FieldDescriptor, Object> '
          'getExtensionFields() { return super.getExtensionFields(); }')

_ENTRY_POINT = '// @@protoc_insertion_point(class_scope:protoserv.RequestProto)'

orig_file = open(sys.argv[1], 'r')
content = orig_file.read()
orig_file.close()

if content.find(_PATCH) >= 0:
  print >>sys.stderr, 'Already patched.'
  sys.exit(0)

entry_idx = content.find(_ENTRY_POINT)
if entry_idx < 0:
  print >>sys.stderr, 'Could not find entry point.'
  sys.exit(1)

new_file = open('%s.new' % sys.argv[1], 'w')
new_file.write(content[:entry_idx])
new_file.write('%s\n' % _PATCH)
new_file.write(content[entry_idx:])
new_file.close()

bkp_file = open('%s.bkp' % sys.argv[1], 'w')
bkp_file.write(content)
bkp_file.close()
for i in range(1, 10000):
  for j in range(1, 10000):
    pass
shutil.move('%s.new' % sys.argv[1], sys.argv[1])
